package littlewhisker.managers {
	import flash.text.Font;
	import flash.display.Sprite;
	import flash.display.MovieClip;

	import littlewhisker.globals.constants.errortypes.LWErrorTypes;
	import flash.display.LoaderInfo;
	import flash.display.DisplayObject;
	
	import littlewhisker.globals.constants.eventtypes.LWEventTypes;

	import flash.events.Event;	
	
	
	import br.com.stimuli.loading.BulkProgressEvent;	
	
	import flash.events.EventDispatcher;	
	
	import br.com.stimuli.loading.BulkLoader;	
	
	/**
	 * @author Philip
	 */
	public class InitLoadManager extends EventDispatcher {

		private static var loader : BulkLoader;
		private static var cue:XMLList;
		public var percent : Number;
		private static var instance:InitLoadManager;
		private static var allowInstantiation:Boolean;
		
		public function InitLoadManager():void{
			if (!allowInstantiation) {
            	throw new Error(LWErrorTypes.SINGLETON_INSTANSIATION);
			}
		}
		
      	public static function getInstance():InitLoadManager {
       	  if (instance == null) {
       	     allowInstantiation = true;
       	     instance = new InitLoadManager();
       	     allowInstantiation = false;
       	   }
       	  return instance;
       	}
			
		public function load(loadingCue:XMLList) : void {
			cue = loadingCue;
			loader = new BulkLoader(BulkLoader.getUniqueName());
			for(var i : Number = 0 ;i < cue.length(); i++) {
				var url:String = String(cue[i].@file);
				var type:String = String(cue[i].@type);
				var id:String = String(cue[i].@id);
				loader.add(url, {id:id});
			}
			loader.addEventListener(BulkProgressEvent.PROGRESS, progressHandler);
			loader.addEventListener(BulkProgressEvent.COMPLETE, onComplete);
			loader.start();
		}
		
		private function progressHandler(event:BulkProgressEvent) : void {
			percent = event.weightPercent;
			dispatchEvent(event); 
		}
				
		private function removeListeners() : void {
			loader.removeEventListener(BulkProgressEvent.PROGRESS, progressHandler);
			loader.removeEventListener(BulkProgressEvent.COMPLETE, onComplete);
		}
			
		private function onComplete(event:BulkProgressEvent) : void {
			assignAssets();
			removeListeners()
			dispatchEvent(new Event(LWEventTypes.ON_COMPLETE));
		}
		
		private function assignAssets():void{
			for(var i:uint; i<cue.length(); i++){
				var type:String = String(cue[i].@type);
				var id:String = String(cue[i].@id);
				switch (type){
					case "swf":
						var swf:Sprite = (loader.getContent(id) as Sprite);
						AssetManager.addLibrary(swf, id);
						break;
					case "xml":
						var xml:XML = loader.getContent(id) as XML;
						if(id=="xml_test2"){
							var myString:String = String(loader.getContent(id));
							var temp:XML = new XML(myString);
							
						}
						AssetManager.addXML(xml, id);
						break;
				
				}
			}
		
		}
	}
}
